﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using DataAccess;
using com.chttl.ienc.bean;
using java.util;

namespace iEN.Organization
{
    public partial class ControllerManage : System.Web.UI.Page
    {
        #region protected void Page_Load(object sender, EventArgs e) //初始頁面
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dtController = new DBAccess().getControllerTable("1");  //取得ALLOrgGroup
            if (dtController == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('資料庫抓取資料有誤！')", true);
                return;
            }
            this.gvGrpName.DataSource = dtController;
            Session["dtDataSourceTemp"] = dtController;
            this.gvGrpName.DataBind();

            if (Session["SysAdmin"].ToString() != "2")
            {
                Panel1.Visible = false;
                lblMsg.Visible = true;
                btReturn.Visible = false;
                btAddCortrol.Visible = false;
            }
        }
        #endregion

        #region protected void btReturn_Click(object sender, EventArgs e) //回到組織群組管理頁面
        protected void btReturn_Click(object sender, EventArgs e)
        {
            this.Page.Response.Redirect("../Organization/GroupManage.aspx");
        }
        #endregion

        #region public void pageSet(object gvQuery) //分頁設定
        public void pageSet(object gvQuery)
        {
            GridView gv = (GridView)gvQuery;
            if (gv.PageCount > 1)
            {
                if (gv.BottomPagerRow == null)
                    return;
                Label lbCount = (Label)gv.BottomPagerRow.FindControl("lbAllCount");
                Label lbPage = (Label)gv.BottomPagerRow.FindControl("lbAllPage");
                DropDownList ddlJump = (DropDownList)gv.BottomPagerRow.FindControl("dd1PageJump");
                //顯示資料總筆數與總頁數
                lbCount.Text = "共" + (gv.PageSize * gv.PageCount).ToString() + "筆";
                lbPage.Text = "共" + gv.PageCount + "頁";
                //設定下拉選單跳頁之頁數        
                for (int i = 1; i <= gv.PageCount; i++)
                    ddlJump.Items.Add(new ListItem(i.ToString()));
                //first:firstc和previous按鈕無作用;  last: next和last按鈕無作用  
                if (gv.PageIndex == 0)
                {
                    ((Button)gv.BottomPagerRow.FindControl("First")).Enabled = false;
                    ((Button)gv.BottomPagerRow.FindControl("Previous")).Enabled = false;
                }
                else if (gv.PageIndex == (gv.PageCount - 1))
                {
                    ((Button)gv.BottomPagerRow.FindControl("Next")).Enabled = false;
                    ((Button)gv.BottomPagerRow.FindControl("Last")).Enabled = false;
                }
                //顯示目前頁數
                ddlJump.SelectedIndex = gv.PageIndex;
            }
        }

        protected void dd1PageJump_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlpage = ((DropDownList)this.gvGrpName.BottomPagerRow.FindControl("dd1PageJump"));
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = ddlpage.SelectedIndex;
            this.gvGrpName.DataBind();
        }

        protected void Last_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = this.gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = this.gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    intPageIndex = this.gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();
        }

        protected void Next_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = this.gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    if (this.gvGrpName.PageIndex != this.gvGrpName.PageCount)
                        intPageIndex = this.gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();
        }

        protected void Previous_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = this.gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    intPageIndex = gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();
        }

        protected void First_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = this.gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = this.gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    intPageIndex = this.gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();
        }
        #endregion

        #region protected void gvGrpName_RowDeleting(object sender, GridViewDeleteEventArgs e) //刪除控制器
        protected void gvGrpName_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            this.UpdatePanel3.Visible = false;
            this.UpdatePanel2.Visible = false;
            
            DataTable dtTemp = (DataTable)Session["dtDataSourceTemp"];
            int editIndex = e.RowIndex;
            string controllerId = this.gvGrpName.Rows[editIndex].Cells[0].Text;

            bool blnRet = new DBAccess().deleteControllerData(controllerId);

            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            string strMemo = "ID：" + controllerId + "//名稱：" + this.gvGrpName.Rows[editIndex].Cells[1].Text;
            
            if (blnRet == false)
            {
                new DBAccess().addEventLog(strAccount, strIP, 32, strMemo, "0");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('刪除控制器資料有誤！')", true);
                //return;
            }
            else
            {
                new DBAccess().addEventLog(strAccount, strIP, 32, strMemo, "1");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('刪除控制器資料成功！')", true);
                //return;
            }
            //this.Page.Response.Redirect("../Organization/ControllerManage.aspx");
            Panel3Clear();
            Panel4Clear();

            this.Page_Load(this, null);


        }
        #endregion

        #region protected void AddCortrol_Click(object sender, EventArgs e) //新增控制器
        protected void AddCortrol_Click(object sender, EventArgs e)
        {
            this.UpdatePanel2.Visible = false;
            this.UpdatePanel3.Visible = true;
            gvGrpName.SelectedIndex = -1;

            DataTable dtCtrlServer = new DBAccess().getCtrlServerTable("1");
            ddlCtrlServer.Items.Clear();
            for (int i = 0; i < dtCtrlServer.Rows.Count; i++)
            {
                ddlCtrlServer.Items.Add(new ListItem(dtCtrlServer.Rows[i]["_name"].ToString(), dtCtrlServer.Rows[i]["_id"].ToString()));
            }
        }
        #endregion

        #region protected void NoADD_Click(object sender, EventArgs e) //取消新增
        protected void NoADD_Click(object sender, EventArgs e)
        {
            this.UpdatePanel3.Visible = false;
            tbCrtName.Text = "";
            tbDesc.Text = "";
            this.Page.Response.Redirect("../Organization/ControllerManage.aspx");
        }
        #endregion

        #region protected void YesADD_Click(object sender, EventArgs e) //確定新增
        protected void YesADD_Click(object sender, EventArgs e)
        {
            Controller newControl;
            DataTable dtTemp = (DataTable)Session["dtDataSourceTemp"];
            string refID = genRefId(dtTemp);

            if (ddlProtocol.SelectedValue == "MODBUS")
            {
                
                
                //ModbusController modbusController = new ModbusController();
                //modbusController.setCustomerId(1);
                //modbusController.setEnabled(true);
                //modbusController.setName(tbCrtName.Text);//
                //modbusController.setProtocol("MODBUS");
                //modbusController.setFirmware("1.0.0");
                //modbusController.setConnectionType(ConnectionType.SelectedValue);//
                //modbusController.setSlaveUnitId(16); //
                //modbusController.setIp(IP.Text); //
                //modbusController.setPort(502); //
                //modbusController.setModel(ddlModel.SelectedValue);
                //modbusController.setCustomerId(1);
                //modbusController.setDesc(tbDesc.Text);//
                ////DB可null，但送下Box不可為空的欄位
                //modbusController.setManufacturer("");
                //modbusController.setMac("");
                //modbusController.setPortName("COM1");
                //modbusController.setBaudRate(9600);
                //modbusController.setParityCheck("None");
                //modbusController.setDatabits(8);
                //modbusController.setStopBits(1);
                //modbusController.setNetmask("");
                //modbusController.setGateway("");
                //modbusController.setControlServerId(1);
                //modbusController.setRefId(refID);//
                
                ////StatusCode: 499, Description: Unable to store Job with name: '1' and group: 'DataLoggingGroup', 
                ////because one already exists with this identification.

                //newControl = new WebService().createController1(modbusController);

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "名稱：" + tbCrtName.Text;

                bool blnRet = new DBAccess().addControllerData(tbCrtName.Text, ConnectionType.SelectedValue, SlaveUnitId.Text, IP.Text, Port.Text, tbDesc.Text, refID, ddlCtrlServer.SelectedValue);

                if (blnRet == false)
                {
                    new DBAccess().addEventLog(strAccount, strIP, 31, strMemo, "0");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增控制器資料有誤！')", true);
                    //return;
                }
                else
                {
                    new DBAccess().addEventLog(strAccount, strIP, 31, strMemo, "1");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增成功！')", true);
                    //return;
                    
                }

            }
            //else if (ddlProtocol.SelectedValue == "FATEK")
            //{
            //    FatekController fatekController = new FatekController();
            //    fatekController.setCustomerId(1);
            //    fatekController.setEnabled(true);
            //    fatekController.setName(tbCrtName.Text);
            //    fatekController.setProtocol("FATEK");
            //    fatekController.setFirmware("1.0.0");
            //    fatekController.setConnectionType(ConnectionType.SelectedValue);
            //    fatekController.setSlaveUnitId(1); //SlaveUnitId.Text
            //    fatekController.setIp(IP.Text); //IP.Text
            //    fatekController.setPort(500);//Port.Text
            //    fatekController.setModel(ddlModel.SelectedValue);
            //    fatekController.setDesc(tbDesc.Text);
            //    //DB可null，但送下Box不可為空的欄位
            //    fatekController.setManufacturer("");
            //    fatekController.setMac("");
            //    fatekController.setPortName("");
            //    fatekController.setParityCheck("");
            //    fatekController.setNetmask("");
            //    fatekController.setGateway("");
            //    fatekController.setControlServerId(1);
            //    fatekController.setRefId(refID);

            //    newControl = new WebService().createController1(fatekController);
            //    if (newControl == null)
            //    {
            //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增控制器資料有誤！')", true);
            //        this.Page.Response.Redirect("../Organization/ControllerManage.aspx");
            //    }
            //    else
            //    {
            //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增成功！')", true);
            //        this.Page.Response.Redirect("../Organization/ControllerManage.aspx");
            //    }
            //}
            
            this.UpdatePanel3.Visible = false;
            Panel3Clear();
            this.Page_Load(this, null);
            
            //this.Page.Response.Redirect("../Organization/ControllerManage.aspx");
        }
        #endregion

        #region protected void NoEdit_Click(object sender, EventArgs e) //取消修改
        protected void NoEdit_Click(object sender, EventArgs e)
        {
            this.UpdatePanel2.Visible = false;
            this.Page.Response.Redirect("../Organization/ControllerManage.aspx");
        }
        #endregion

        #region protected void YesEdit_Click(object sender, EventArgs e) //確定修改
        protected void YesEdit_Click(object sender, EventArgs e)
        {
            DataTable dtTemp = (DataTable)Session["dtDataSourceTemp"];
            //int editIndex=(int)Session["EditIndex"];
            //int controllerId = Convert.ToInt32(dtTemp.Rows[editIndex]["_id"].ToString());
            //Controller control= new WebService().getController1(controllerId);
            //control.setName(tbControllerName.Text);
            //control.setModel(ControllerModel.SelectedValue);
            //control.setDesc(ControllerDesc.Text);             
            string strID = Session["ID"].ToString();

            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            string strMemo = "ID：" + strID + "//名稱：" + tbControllerName.Text;

            bool blnRet = new DBAccess().updateControllerData(tbControllerName.Text, ddlConnectionType.SelectedValue, tbSlaveUnitId.Text, tbIP.Text, tbPort.Text, ControllerDesc.Text, strID, ddlCtrlServerUpdate.SelectedValue);
            if (blnRet == false)
            {
                new DBAccess().addEventLog(strAccount, strIP, 33, strMemo, "0");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('修改控制器資料有誤！')", true);
                //return;
            }
            else
            {
                new DBAccess().addEventLog(strAccount, strIP, 33, strMemo, "1");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('修改控制器資料成功！')", true);
                //return;
            }

            this.UpdatePanel2.Visible = false;
            Panel4Clear();
            //this.Page.Response.Redirect("../Organization/ControllerManage.aspx");
            this.Page_Load(this, null);
        }
        #endregion

        #region protected void gvGrpName_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) //修改控制器
        protected void gvGrpName_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            this.UpdatePanel3.Visible = false;
            this.UpdatePanel2.Visible = true;
            Session["EditIndex"] = e.NewSelectedIndex;
            Session["ID"] = this.gvGrpName.Rows[e.NewSelectedIndex].Cells[0].Text;

            DataTable dtCtrlServer = new DBAccess().getCtrlServerTable("1");
            ddlCtrlServerUpdate.Items.Clear();
            for (int i = 0; i < dtCtrlServer.Rows.Count; i++)
            {
                ddlCtrlServerUpdate.Items.Add(new ListItem(dtCtrlServer.Rows[i]["_name"].ToString(), dtCtrlServer.Rows[i]["_id"].ToString()));
            }

            DataTable dtDataSourceTemp = (DataTable)Session["dtDataSourceTemp"];
            dtDataSourceTemp.DefaultView.RowFilter = "_id=" + this.gvGrpName.Rows[e.NewSelectedIndex].Cells[0].Text;
            dtDataSourceTemp = dtDataSourceTemp.DefaultView.ToTable();

            ddlCtrlServerUpdate.SelectedValue = dtDataSourceTemp.Rows[0]["_ctrl_server_id"].ToString();

            tbControllerName.Text = this.gvGrpName.Rows[e.NewSelectedIndex].Cells[1].Text;
            ControllerModel.Text = this.gvGrpName.Rows[e.NewSelectedIndex].Cells[2].Text;

            ControllerProto.SelectedItem.Text = this.gvGrpName.Rows[e.NewSelectedIndex].Cells[3].Text;

            if (this.gvGrpName.Rows[e.NewSelectedIndex].Cells[5].Text == "&nbsp;")
            {
                ControllerDesc.Text = "";
            }
            else
                ControllerDesc.Text = this.gvGrpName.Rows[e.NewSelectedIndex].Cells[5].Text;

            

            DataTable dtController = new DBAccess().getModbusControllerTable(this.gvGrpName.Rows[e.NewSelectedIndex].Cells[0].Text);
            tbSlaveUnitId.Text = dtController.Rows[0]["_slave_unit_id"].ToString();
            tbIP.Text = dtController.Rows[0]["_ip"].ToString();
            tbPort.Text = dtController.Rows[0]["_port"].ToString();
            //ddlConnectionType.SelectedItem.Text = dtController.Rows[0]["_connection_type"].ToString();

            for (int i = 0; i < ddlConnectionType.Items.Count; i++)
            {
                ddlConnectionType.Items[i].Selected = false;
                if (ddlConnectionType.Items[i].Text == dtController.Rows[0]["_connection_type"].ToString())
                {
                    ddlConnectionType.Items[i].Selected = true;
                }
            }


        }
        #endregion

        #region private string genRefId(DataTable DT) //產生Ref_ID
        private string genRefId(DataTable DT)
        {
            string result = "";
            bool checkFlag = true;
            char[] key = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
                                      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
                                      'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
                                      'u', 'v', 'w', 'x', 'y', 'z',
                                      'A', 'B', 'C', 'D', 'E', 'f', 'G', 'H', 'I', 'J', 
                                      'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
                                      'U', 'V', 'W', 'X', 'Y', 'Z'};
            DataTable dtBuffer;

            System.Random rndGen = new System.Random();

            while (checkFlag == true)
            {
                result = "";

                for (int i = 0; i < 16; i++)
                {
                    int rnd = rndGen.Next(0, 62);
                    result += key[rnd];
                }

                DT.DefaultView.RowFilter = "_ref_id = '" + result + "'";
                dtBuffer = DT.DefaultView.ToTable();

                if (dtBuffer.Rows.Count == 0)
                    checkFlag = false;
            }

            return result;
        }
        #endregion

        #region protected void gvGrpName_RowDataBound(object sender, GridViewRowEventArgs e)
        protected void gvGrpName_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells[0].Visible = false;
        }
        #endregion

        #region private void Panel3Clear() //清除新增資料
        private void Panel3Clear()
        {
            ddlConnectionType.SelectedIndex = 0;
            tbControllerName.Text = "";
            tbSlaveUnitId.Text = "";
            tbIP.Text = "";
            tbPort.Text = "";
            ControllerDesc.Text = "";

        }
        #endregion

        #region private void Panel4Clear() //清除修改資料
        private void Panel4Clear()
        {
            ConnectionType.SelectedIndex = 0;
            tbCrtName.Text = "";
            SlaveUnitId.Text = "";
            IP.Text = "";
            Port.Text = "";
            tbDesc.Text = "";

        }
        #endregion
    }
}